//
//  GameViewController.m
//  2048-for-ios
//
//  Created by User-08 on 4/15/14.
//  Copyright (c) 2014 IOTrainingCamp. All rights reserved.
//

#import "GameViewController.h"

#import "GameOverViewController.h"

#import "config.h"

#import "IOTCGame.h"

@interface GameViewController ()

@property (nonatomic) UIView* generalView;

//placeholders for the tiles
@property (nonatomic) NSMutableArray* arrayWithGrid;
@property (strong)IOTCGame* game;

@end

@implementation GameViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //init the game. migth be a job for the level loader to set size
     self.game = [IOTCGame sharedInstance];
    self.game.delegate = self;
    
    self.generalView = [[UIView alloc] init];
    self.generalView.backgroundColor = kBoardColor;
    [self.view addSubview:self.generalView];
    self.arrayWithGrid = [NSMutableArray arrayWithCapacity:kViewArraySizeUp];
    
    //init the tile placeholders
    for (int i = 0; i < kViewArraySizeUp; i++) {
        NSMutableArray* currentArray = [NSMutableArray arrayWithCapacity:kViewArraySizeSide];
        [self.arrayWithGrid insertObject:currentArray atIndex:i];
    }
    
    for (int i = 0; i < kViewArraySizeUp; i++) {
        for (int j = 0; j < kViewArraySizeUp; j++) {
            UIView* blankView = [[UIView alloc] init];
            [[self.arrayWithGrid objectAtIndex:i] insertObject:blankView atIndex:j];
            [blankView setBackgroundColor:[UIColor whiteColor]];
            [self.generalView addSubview: blankView];
        }
    }
    
    //this shold depend on the level
    [self.game loadANewGameWithSize:CGPointMake(kViewArraySizeUp, kViewArraySizeSide)];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - game delegate

-(void) updateTileAtIndex:(NSIndexPath*) index
{
    
    
    NumberView* viewToAdd = [self.game numberViewForIndexPath:index];
    
    [self AddNumberView:viewToAdd toTileAtIndex:index];
    
}


-(void)gameOverWithReason:(GameEndReason)reason {
    GameOverViewController* gameOverScreen = [[GameOverViewController alloc] init];
    gameOverScreen.gameEndReason = reason;
    
    //TODO: might not be the most efficient way to create a new VC every time the game ends :)
    [self.navigationController addChildViewController:gameOverScreen];
    [self.navigationController.view addSubview:gameOverScreen.view];
    
    [gameOverScreen.view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.navigationController.view addConstraint:[NSLayoutConstraint constraintWithItem:self.navigationController.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:gameOverScreen.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.navigationController.view addConstraint:[NSLayoutConstraint constraintWithItem:self.navigationController.view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:gameOverScreen.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    [self.navigationController.view addConstraint:[NSLayoutConstraint constraintWithItem:self.navigationController.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:gameOverScreen.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    [self.navigationController.view addConstraint:[NSLayoutConstraint constraintWithItem:self.navigationController.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:gameOverScreen.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];
    //[self.navigationController pushViewController:gameOverScreen animated:YES];
    
}

//animations
-(void) moveNumberViewAtIndex:(NSIndexPath*) fromIndex toIndex:(NSIndexPath*) toIndex {
    
    //extract the participants in the animation
    NumberView* tile = [[[[self.arrayWithGrid objectAtIndex:fromIndex.row] objectAtIndex:fromIndex.section] subviews] objectAtIndex:0];
    
    // define the completion block
    void(^completion)(BOOL finished)= ^(BOOL finished) {
        //remove tile from the game board and add it where it belongs
        [tile removeFromSuperview];
        [self updateTileAtIndex:toIndex];
        
    };
    
    [self moveNumberView:tile FromtIndex:fromIndex toIndex:toIndex withCompletion:completion];
    
}

-(void) moveNumberViewWithAdditionFromIndex:(NSIndexPath*) fromIndex toIndex:(NSIndexPath*) toIndex {
    
    NumberView* tile = [[[[self.arrayWithGrid objectAtIndex:fromIndex.row] objectAtIndex:fromIndex.section] subviews] objectAtIndex:0];
    UIView* additionCell = [[self.arrayWithGrid objectAtIndex:toIndex.row] objectAtIndex:toIndex.section];
    
    void(^additionAnimation)(void)= ^(void) {
        NumberView* newTile = [self.game numberViewForIndexPath:toIndex];
        newTile.frame = additionCell.frame;
        newTile.center = additionCell.center;
        [self.generalView addSubview:newTile];
        void (^animation) (void) = ^{
            NSLog(@"animating");
            newTile.transform = CGAffineTransformMakeScale(2, 2);
            
        };
        [UIView animateWithDuration:0.1
                              delay:0
                            options:UIViewAnimationOptionAutoreverse
                         animations:animation completion:^(BOOL finished){
                             [newTile removeFromSuperview];
                             newTile.transform = CGAffineTransformMakeScale(1, 1);
                             
                             [self AddNumberView:newTile toTileAtIndex:toIndex];
                         }];
        
        
    };
    
    // define the completion block
    void(^completion)(BOOL finished)= ^(BOOL finished) {
        //remove tile from the game board and add it where it belongs
        [tile removeFromSuperview];
        additionAnimation();
        
    };
    
    [self moveNumberView:tile FromtIndex:fromIndex toIndex:toIndex withCompletion:completion];
    
}

-(void) newTileSpawnAtIndex:(NSIndexPath *)index
{
    NumberView* newSpawned = [[self.arrayWithGrid objectAtIndex:index.row]objectAtIndex:index.section];
    newSpawned.transform = CGAffineTransformMakeScale(0, 0);
    
    void(^spawnAnitmation)(void) = ^{
        newSpawned.transform = CGAffineTransformMakeScale(1.5, 1.5);
    };
    
    
    [UIView animateWithDuration:0.2
                          delay:0
                        options: UIViewAnimationOptionTransitionNone animations:spawnAnitmation completion: ^(BOOL finished) {
                            newSpawned.transform = CGAffineTransformMakeScale(1, 1);
                            
                        }];
}

#pragma mark - private methods

//sets the constraints when a number view should be added to a placeholder tile
- (void)AddNumberView:(NumberView *)viewToAdd toTileAtIndex:(NSIndexPath *)index
{
    UIView* cell = [[self.arrayWithGrid objectAtIndex:index.row] objectAtIndex:index.section];
    
    if([[cell subviews] count] > 0){
        [[[cell subviews] objectAtIndex:0] removeFromSuperview];
    }
    [cell addSubview: viewToAdd];
    
    [viewToAdd setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [cell removeConstraints:cell.constraints];
    
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:viewToAdd attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:viewToAdd attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:viewToAdd attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:viewToAdd attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];
}


//move the content of one tile to another animated
-(void)  moveNumberView:(NumberView*) tile FromtIndex:(NSIndexPath*) fromIndex toIndex:(NSIndexPath*) toIndex  withCompletion:(void(^)(BOOL))completion{
    
    //extract the participants in the animation
    UIView* cellToMoveFrom =[[self.arrayWithGrid objectAtIndex:fromIndex.row] objectAtIndex:fromIndex.section];
    UIView* cellToMoveTo =[[self.arrayWithGrid objectAtIndex:toIndex.row] objectAtIndex:toIndex.section];
    // define the animation block
    void(^animation) (void) = ^{
        
        tile.center = cellToMoveTo.center;
        
    };
    
    // add the tile to the game board where the animation is performed
    tile.frame = cellToMoveFrom.frame;
    
    //tile.clipsToBounds = YES;
    [self updateTileAtIndex:fromIndex];
    [self.generalView addSubview:tile];
    
    //[UIView transitionWithView:tile duration:2 options:UIViewAnimationOptionTransitionCrossDissolve animations:animation completion:completion];
    [UIView animateWithDuration:0.2    animations: animation                    completion:completion];
}

-(void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    [self.generalView removeConstraints:[self.generalView constraints]];
    [self.generalView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    // board constraints
    double maxSize = MIN(self.view.frame.size.width, self.view.frame.size.height);
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.generalView attribute:NSLayoutAttributeCenterX relatedBy: NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.generalView attribute:NSLayoutAttributeCenterY relatedBy: NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    
    [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:self.generalView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0 constant:maxSize]];
    
    [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:self.generalView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0 constant: maxSize]];
    
    //tile placeholder constraints
    for (int i = 0; i < kViewArraySizeUp; i++) {
        for (int j = 0; j < kViewArraySizeSide; j++) {
            
            UIView* cell = [[self.arrayWithGrid objectAtIndex:i] objectAtIndex:j];
            [cell setTranslatesAutoresizingMaskIntoConstraints:NO];
            
            [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeCenterX relatedBy: NSLayoutRelationEqual toItem:self.generalView attribute:NSLayoutAttributeCenterX multiplier:1.0/kViewArraySizeSide + 2.0/kViewArraySizeSide * j constant:0]];
            
            [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeCenterY relatedBy: NSLayoutRelationEqual toItem:self.generalView attribute:NSLayoutAttributeCenterY multiplier:1.0/kViewArraySizeUp + 2.0/kViewArraySizeUp * i constant:0]];
            
            [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.generalView attribute:NSLayoutAttributeWidth multiplier:1.0/kViewArraySizeSide constant:-1*kTileMargin*(kViewArraySizeSide+1)/kViewArraySizeSide]];
            
            [self.generalView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.generalView attribute:NSLayoutAttributeHeight multiplier:1.0/kViewArraySizeUp constant:-1*kTileMargin*(kViewArraySizeUp+1)/kViewArraySizeUp]];
        }
    }
    
}





@end
